package com.eazy.lkv2.web.controller.system;


import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.eazy.lkv2.core.web.utils.AddrUtils;
import com.eazy.lkv2.core.web.utils.MD5;
import com.eazy.lkv2.core.web.utils.StrKit;
import com.eazy.lkv2.web.controller.BaseController;
import com.eazy.lkv2.web.entity.LoginLog;
import com.eazy.lkv2.web.service.system.count.BaiduService;

/**
 * @author jzx
 * @desc 登录管理
 * @date 2016.06.16
 */
@Controller
@RequestMapping("/sys")
public class SystemLoginController extends BaseController {
	
	@Autowired
	private BaiduService baiduService;
	
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = { RequestMethod.POST})
	public String login(RedirectAttributes flash) {
		Map<String, String>  map = getPageData(request);

		if(StrKit.isEmpty(map.get("name")) && StrKit.isEmpty(map.get("pwd")) ) {
			flash.addFlashAttribute("msg", "用户名和密码不能为空");
		}
		else if(StrKit.isEmpty(map.get("name"))) {
			flash.addFlashAttribute("msg", "用户名不能为空");
		}
		else if(StrKit.isEmpty(map.get("pwd"))) {
			flash.addFlashAttribute("msg", "密码不能为空");
		} 
		 else {
			// 需要的时候再去拿session
			String code = getAttrSessionToStr("code");

			if (!code.equalsIgnoreCase(map.get("code"))) {
				flash.addFlashAttribute("msg", "验证码输入错误");
			} else {
				try {
					UsernamePasswordToken token = new UsernamePasswordToken(map.get("name"),MD5.encodeString(map.get("pwd")));
					token.setRememberMe(true);
					Subject currentUser = SecurityUtils.getSubject();
					currentUser.login(token);
					// 验证是否登录成功
					if (currentUser.isAuthenticated()) {
						// 删除产生的废弃验证码
						removeAttrSession(map.get("code"));
						
						// 加入一些小功能 2016-07-14 实现百度地图统计的
						
						// 改进意见，底层mybatis 封装的不太好，如果不想添加某些字段报错太恶心了实在是
						String ipAddr = getIpAddr();
						
						if(!ipAddr.equals("0:0:0:0:0:0:0:1")) {
							JSONObject data = AddrUtils.requestGet(AddrUtils.LOCATION + ipAddr);
							
							LoginLog login_log = new LoginLog();
							
							login_log.setAccount(getCurrentUser().getName());
							login_log.setLoginIp(getIpAddr());
							login_log.setLoginTime(getSysTimestamp());
							login_log.setDetailAddress(data.getString("address"));
							
							JSONObject contentJsonObject = data.getJSONObject("content");
							 if (contentJsonObject != null) {
								 login_log.setAddress(contentJsonObject.getString("address"));
								 JSONObject point = contentJsonObject.getJSONObject("point");
								 if (point != null) {
									 login_log.setPointX(point.getBigDecimal("x"));
									 login_log.setPointY(point.getBigDecimal("y"));
	                             }
								 JSONObject address_detailJsonObject = contentJsonObject.getJSONObject("address_detail");
	                             if (address_detailJsonObject != null) {
	                            	 login_log.setProvince(address_detailJsonObject.getString("province"));
	                            	 login_log.setCity(address_detailJsonObject.getString("city"));
	                            	 login_log.setCityCode(address_detailJsonObject.getString("city_code"));
	                             }
							 }
							baiduService.create(login_log);
						}
						return "redirect:/system/login";
					} else {
						token.clear();
					}
				} catch (AuthenticationException ex) {
					flash.addFlashAttribute("msg", "用户名或者密码输入错误!!!");
				}
			}
		}
		return "redirect:login";
	}
	
	/**
	 * 用户登出
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "system/login";
	}
	
	/**
	 * 登录失败
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String fail(ModelMap model)  {
		return "system/login";
	}
	
}
